package com.wlanauth.web.util;

import java.util.Map;
import java.util.Map.Entry;
import java.util.concurrent.ConcurrentHashMap;
/**
 * 简单缓存管理
 * @author zz
 * @date 2012-5-23
 * @email charles.zz.life@gmail.com
 */
public class SimpleCacheManager {
	
	private static final Map<String,Object> cacheMap = new ConcurrentHashMap<String,Object>();
	private static final Map<String,Long> cacheTimerMap = new ConcurrentHashMap<String,Long>();
	
	public static SimpleCacheManager instance;//实例
	
	private static int timeout = 1000*60*5;//5min
	private SimpleCacheManager(){}
	public synchronized static SimpleCacheManager getInstance(){
		if(instance == null){
			System.out.println("实列化缓存...");
			instance = new SimpleCacheManager();
			Thread t = new Thread(new Runnable(){

				public void run() {
					while(true){
						//System.out.println("清理缓存");
						try {
							Thread.sleep(60*1000);
							long now = System.currentTimeMillis();
							for(Entry<String,Long> t:cacheTimerMap.entrySet()){
								if(now - t.getValue()>=timeout){
									cacheMap.remove(t.getKey());
								}
							}
							
						} catch (InterruptedException e) {
							
						}//1min
					}
				}
				
			});
			t.setDaemon(true);
			t.start();
		}
		return instance;
	}
	public Object get(String key){
		Object obj = cacheMap.get(key);
		if(obj!=null){
			cacheTimerMap.put(key, System.currentTimeMillis());
		}
		return obj;
	}
	public void put(String key,Object obj){
		cacheMap.put(key, obj);
		cacheTimerMap.put(key, System.currentTimeMillis());
	}

}
